package icu.shaoyayu.security.dome1.config;

import icu.shaoyayu.security.dome1.handler.MyAuthenticFailureHandler;
import icu.shaoyayu.security.dome1.handler.MyAuthenticSuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author shaoyayu
 * @Version 1.0.0
 * @readme ：
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //自定义的登录页面
        http.formLogin()
                /*自定义登录参数,必须和前端FORM表单中的请求相同*/
                .usernameParameter("userName")
                .passwordParameter("userPassword")
                /*处理登录请求的地址*/
                .loginProcessingUrl("/login")
                .loginPage("/login.html")
                /*登录成功后必须返回的连接是POST请求，在POST请求中使用重定向*/
//                .successForwardUrl("/toMain")
                .successHandler(new MyAuthenticSuccessHandler("https://www.baidu.com"))
                /*登录失败，也是一个POST的请求*/
//                .failureForwardUrl("/toError");
                .failureHandler(new MyAuthenticFailureHandler("/loginFailed.html"));
        //所有资源都必须经过认证才能访问
        http.authorizeRequests()
                //未授权的情况下，准许访问的资源
                .antMatchers("/login.html").permitAll()
                .antMatchers("/loginFailed.html").permitAll()
                /*静态资源的允许访问*/
                .antMatchers("/images/**","/css/**","/js/**").permitAll()
                /*通过正则表单时放行*/
                .regexMatchers(".+[.]png").permitAll()
                /*其他的资源必须授权*/
                .anyRequest().authenticated();
        /*暂时关闭跨站脚本攻击防护*/
        http.csrf().disable();

    }

    @Bean
    public PasswordEncoder getWe(){
        return new BCryptPasswordEncoder();
    }

}
